package com.pianzhu.blockchainemr.interceptor;
//import com.pianzhu.blockchainemr.utils.CurrentHolder;
import com.pianzhu.blockchainemr.utils.CurrentHolder;
import com.pianzhu.blockchainemr.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        log.info("Interceptor get requestURI: {}, Method: {}", requestURI, method);

        // 关键：放行 OPTIONS 预检请求
        if ("OPTIONS".equalsIgnoreCase(method)) {
            log.info("OPTIONS 预检请求，直接放行");
            return true;
        }

        // 排除不需要 token 的接口
        if (requestURI.contains("/login") || requestURI.contains("/enroll") || requestURI.contains("/hospital/list")) {
            log.info("公开接口，放行: {}", requestURI);
            return true;
        }

        //3.获取token
        String token = request.getHeader("token");
        log.info("获取到的token: {}", token);

        //4.判断token是否为存在，如果不存在，则返回401
        if (token == null || token.isEmpty()) {
            log.error("no token for request: {}", requestURI);
            response.sendError(401, "token is null");
            return false;
        }

        //5.校验token是否正确，如果不正确，则返回401
        try {
            Claims claims = JWTUtils.parseJWT(token);
            Integer userId = claims.get("id", Integer.class);
            String username = claims.get("username", String.class);
            String usertype = claims.get("usertype", String.class);
            CurrentHolder.setCurrentLocal(username);
            log.info("token校验通过，用户ID: {}, 用户名: {}, 用户类型: {}, 请求: {}", userId, username, usertype, requestURI);
        } catch (Exception e) {
            log.error("token解析失败: {}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //6.如果token正确，则放行
        log.info("token校验通过，放行: {}", requestURI);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentHolder.removeCurrentLocal();
    }
}